<script setup lang="ts">
import { OrderPaymentStatus, OrderPaymentStatusInfo, SjWareDocVo } from '@/api/wuliu';
import { exportWares, listManage, updateWares,sendMessage } from '@/api/wuliu/wares';
import { WaresDocQuery, WaresDocVo, WaresForm, WaresQuery } from '@/api/wuliu/wares/types';
import AreaSelector from '@/components/AreaSelector/AreaSelector.vue';
import { Refresh, Search } from '@element-plus/icons-vue';
import { DrivecarForm, DrivecarQuery, DrivecarVO } from '@/api/wuliu/drivecar/types';
import OrderMx from '@/components/OrderMx/OrderMx.vue';

const loading = ref(false);
const listQuery = reactive<WaresDocQuery>({ pageNum: 1, pageSize: 10, deptId: undefined, bdrmc: undefined });
const listData = ref<WaresDocVo[]>([]);

async function getOrderData() {
  try {
    loading.value = true;

    const { rows } = await listManage(listQuery);
    listData.value = rows;
    console.log('wo de ding dan list', rows);
  } catch (error) {
    console.error('Error get area order list', error);
  } finally {
    loading.value = false;
  }
}

async function saveMessage(id) {
  try {
    loading.value = true;

    const { rows } = await sendMessage(id);
    proxy?.$modal.msgSuccess('发送消息成功');
    getOrderData();
    console.log('wo de ding dan list', rows);
  } catch (error) {
    console.error('Error get area order list', error);
  } finally {
    //loading.value = false;
  }
}

watch(listQuery, getOrderData, { immediate: true });

async function handleExportItem(item: WaresDocVo) {
  try {
    requesting.value = true;
    exportWares(item);
    console.log('export item', item);
  } catch (error) {
    console.error('Error export item', error);
  } finally {
    requesting.value = false;
  }
}

const requesting = ref(false);
const modifyItem = ref<WaresDocVo>();

function beforeModifyClose() {
  return !requesting.value;
}

async function handleUpdateItem() {
  const item = toRaw(modifyItem.value);

  if (!item) {
    return;
  }

  try {
    requesting.value = true;
    const { id, paidAmount } = item;
    await updateWares({ id, paidAmount });
    console.log('update item', item);
  } catch (error) {
    console.error('Error update item', error);
  } finally {
    requesting.value = false;
    handleCloseModifyPaidAmount();
    getOrderData();
  }
}

const modifyPaidAmountVisible = ref(false);

function handleOpenModifyPaidAmount(item: WaresDocVo) {
  modifyItem.value = { ...toRaw(item) };
  modifyPaidAmountVisible.value = true;
}

function handleCloseModifyPaidAmount() {
  modifyPaidAmountVisible.value = false;
}

watch(listQuery, getOrderData, { immediate: true });
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const showSearch = ref(true);
const orderMxRef = ref<InstanceType<typeof OrderMx>>();
const detailVisible = ref(false);


/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('wuliu/wares/export2', {
    ...listQuery
  }, `ware_${new Date().getTime()}.xlsx`)
}

/** 导出按钮操作 */
const handleExportForId = (id) => {
  proxy?.download('wuliu/wares/export2', {
    id
  }, `ware_${new Date().getTime()}.xlsx`)
}

//查看明细
// function openMx(item: any) {
//   console.log('Mx', item.wareDocMxVoList);
//   orderMxRef.value?.handleOpen(item.wareDocMxVoList);
// }

async function openMx(item: SjWareDocVo) {
  console.log('Detail', item);
  orderMxRef.value = item.wareDocMxVoList;
  detailVisible.value = true;
}

</script>

<template>

  <div class="app-container wo-de-ding-dan">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
    <div v-show="showSearch" class="header">
      <div class="header-filter">
        <el-form ref="queryFormRef" :model="listQuery" :disabled="loading" :inline="true">
          <el-form-item label="所属区域" prop="deptId">
            <AreaSelector v-model="listQuery.deptId" />
          </el-form-item>
          <el-form-item label="客户名称" prop="bdrmc">
            <el-input v-model="listQuery.bdrmc" />
          </el-form-item>
<!--          <el-form-item label="结算状态" prop="paymentStatus">-->
<!--            <el-select v-model="listQuery.paymentStatus">-->
<!--              <el-option-->
<!--                v-for="item in [-->
<!--                  { label: '全部状态', value: undefined },-->
<!--                  ...[OrderPaymentStatus.wait, OrderPaymentStatus.done].map((value) => {-->
<!--                    return { value, label: OrderPaymentStatusInfo[value] };-->
<!--                  })-->
<!--                ]"-->
<!--                :key="item.value"-->
<!--                :label="item.label"-->
<!--                :value="item.value"-->
<!--              />-->
<!--            </el-select>-->
<!--          </el-form-item>-->

          <el-form-item label="报单时间" prop="bdTime">
            <el-date-picker clearable
                            v-model="listQuery.bdTime"
                            type="date"
                            value-format="YYYY-MM-DD"
                            placeholder="请选择发车人时间"
            />
          </el-form-item>
<!--          <el-form-item label="报单时间" prop="createTime">-->
<!--            <el-date-picker v-model="listQuery.createTime" type="daterange" />-->
<!--          </el-form-item>-->
        </el-form>
      </div>
      <div class="header-actions">
        <el-tooltip content="刷新">
          <el-button :icon="Refresh" circle @click="getOrderData" />
        </el-tooltip>
      </div>
    </div>
    </transition>
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['wuliu:drivecar:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getOrderData"></right-toolbar>
        </el-row>
      </template>
    </el-card>
    <el-table v-loading="loading" :data="listData" stripe>
      <el-table-column label="客户名称" prop="bdrmc" />
      <el-table-column label="区域" prop="deptId" />
      <el-table-column label="总件数" prop="wareSum">
        <template #default="{ row }"> {{ row.articleSum }}件 </template>
      </el-table-column>
      <el-table-column label="共计运费">
        <template #default="{ row }"> ￥{{ row.priceSum }} </template>
      </el-table-column>
      <el-table-column label="已付运费">
        <template #default="{ row }">
          <span>￥{{ row.paidAmount }}</span>
          <el-button type="primary" size="small" :style="{ marginLeft: '2px' }" text @click="handleOpenModifyPaidAmount(row)">
            <el-icon> <EditPen /></el-icon>
          </el-button>
        </template>
      </el-table-column>
<!--      <el-table-column label="结算状态">-->
<!--        <template #default="{ row }">{{ OrderPaymentStatusInfo[row.paymentStatus] }}</template>-->
<!--      </el-table-column>-->
      <el-table-column label="报单时间" prop="createTime" />
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="primary" size="small" text @click="handleExportForId(row.id)">导出</el-button>
          <el-button type="primary" size="small" text @click="saveMessage(row.id)">提醒</el-button>
          <el-button :icon="Search" type="primary" size="small" text @click="openMx(row)"> 查看 </el-button>

          <!--          <router-link to="/drivecar">About Page</router-link>-->
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="modifyPaidAmountVisible" title="修改已付运费" width="300" :before-close="beforeModifyClose">
      <el-input-number v-model="modifyItem.paidAmount" :min="0" :precision="2" />

      <template #footer>
        <div class="dialog-footer">
          <el-button :disabled="requesting" @click="handleCloseModifyPaidAmount">取消</el-button>
          <el-button :loading="requesting" :disabled="requesting" type="primary" @click="handleUpdateItem">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <el-drawer v-model="detailVisible" title="订单信息" direction="rtl" size="60%">
      <el-table :data="orderMxRef">
        <el-table-column prop="customName" label="收货人名称" />
        <el-table-column prop="number" label="件数" />
        <el-table-column prop="area" label="方数" />
        <el-table-column prop="univalence" label="单价" />
        <el-table-column prop="totalPrice" label="总运费" />
        <el-table-column prop="createTime" label="创建时间" />
      </el-table>
    </el-drawer>
  </div>
</template>

<style lang="scss">
.wo-de-ding-dan {
  display: flex;
  flex-direction: column;

  .header {
    display: flex;
    align-items: center;
    margin-bottom: 10px;

    .header-filter {
      flex: 1 0 0;
    }

    .header-actions {
      flex: 0 0 auto;
    }
  }
}
</style>
